jQuery.noConflict();
(function(PLUGIN_ID) {

    "use strict";

    var config = kintone.plugin.app.getConfig(PLUGIN_ID);
    if (!config) { return false; }
    var rowCount = Number(config["rowCount"]);
    var year = {};
    var age = {};
    var pluginDate = {};
    var yearBase = {};

    for (var i = 0; i < rowCount; i++) {
        year[i] = config["year" + i];
        age[i] = config["age" + i];
        pluginDate[i] = config["pluginDate" + i];
        yearBase[i] = config["yearBase" + i];
    }
    //var flg = false;
    kintone.events.on('app.record.index.show', onIndexShow);

    function createCursor(){
        const fields = ['$id'];
        let condition = '';
        const or = ' or ';
        for (let i = 0;i<rowCount;i++){
            const year = config['year' + i];
            const age = config['age' + i];
            const pluginDate = config['pluginDate' + i];
            fields.push(year);
            fields.push(age);
            fields.push(pluginDate);
            condition += '(' + year + '!= "" and ' + pluginDate + ' <= TODAY())' + or
            + '(' + year + '="" and(' + age +'!=0' + or + pluginDate + '!=""))' + or;
        }
        const body = {
            'app':kintone.app.getId(),
            'fields':fields,
            'query':condition.slice(0,condition.length-or.length),
            'size':500
        }
        return kintone.api(kintone.api.url('/k/v1/records/cursor', true), 'POST', body).then(function(r){
            return r.id;
        });
    }

    function getRecordsByCursor(id, onResult){
        const body = {
            'id':id
        }
        return kintone.api(kintone.api.url('/k/v1/records/cursor', true), 'GET', body).then(function(r){
            onResult(r);
            if (r.next) {
                return getRecordsByCursor(id,onResult);
            }
        })
    }

    function updateRemote(json){
        return kintone.api(kintone.api.url('/k/v1/records', true), 'PUT', json);
    }

    function calculate(data){
        const records = data.records;
        const count = Math.ceil(records.length/100);
        for (let l = 0;l<count;l++){
            const json = {};
            json['app'] = kintone.app.getId();
            json['records']  = [];
            let i = l*100;
            const end = Math.min(i+100,records.length);
            for(i;i < end; i++) {
                const record = {};
                record['id'] = records[i]['$id'].value;
                record['record'] = {};
                for (let j = 0; j < rowCount; j++){
                    const base = Number(config["yearBase" + j]);
                    const startYear = records[i][config['year' + j]].value;
                    const age = config['age' + j];
                    const pluginDate = config['pluginDate' + j];
                    let ageValue = 0;
                    let pluginDateValue = '';
                    if (startYear) {
                        ageValue = Number(moment().diff(moment(startYear),'years')) + base;
                        pluginDateValue = moment(startYear).add(ageValue+1-base,'years').format('YYYY-MM-DD');
                    }
                    record['record'][age] = { 'value':ageValue };
                    record['record'][pluginDate] = { 'value': pluginDateValue };
                }
                json['records'].push(record);
            }
            updateRemote(json);
        }
        if(count >0 && !data.next){
            alert("Processing completed!");
            location.reload();
        } 
    }

    function onIndexShow(event){
       return createCursor().then(function(id){
            return getRecordsByCursor(id,calculate);
        }).catch(function (error) {
            event.error = error;
            return event;
        });
    }

    // // Loop get more than 100 datas
    // function loopGet(offset){
    //     var today = moment().format('YYYY-MM-DD');
    //     var condition = '';
    //     for (var j = 0; j < rowCount; j++){
    //         if (j == rowCount - 1) {
    //             condition = condition + pluginDate[j] + ' <= "' + today + '"';
    //         } else {
    //             condition = condition + pluginDate[j] + ' <= "' + today + '" or ';
    //         }
    //     }

    //     var param = {
    //         app:kintone.app.getId(),
    //         query: condition + ' limit 100 offset ' + offset
    //     };

    //     kintone.api(kintone.api.url('/k/v1/records', true), 'GET', param,
    //     function(resp) {
    //         var records = resp.records;
    //         if(records.length != 0){
    //             var json = {};
    //             json['app'] = kintone.app.getId();
    //             json['records']  = new Array();
    //             for(var i = 0;i < records.length; i++){
    //                 var subRec = {};
    //                 subRec['id'] = records[i]['$id']['value'];
    //                 subRec['record'] = {};
    //                 for (var j = 0; j < rowCount; j++){
    //                     var startYear = records[i][year[j]]['value'];
    //                     var a = moment();
    //                     var b = moment(startYear);
    //                     subRec['record'][age[j]] = {};
    //                     subRec['record'][age[j]]['value'] = Number(a.diff(b,'years')) + Number(yearBase[j]);
    //                     subRec['record'][pluginDate[j]] = {};
    //                     subRec['record'][pluginDate[j]]['value'] = moment(records[i][year[j]]['value']).add(Number(subRec['record'][age[j]]['value'])+1-Number(yearBase[j]),'years').format('YYYY-MM-DD');
    //                 }
    //                 json['records'].push(subRec);
    //             }

    //             kintone.api(kintone.api.url('/k/v1/records', true), 'PUT', json, function(resp){
    //                 flg = true;
    //                 offset = offset + 100;
    //                 loopGet(offset);
    //                 return;
    //             }, function(resp) {
    //                 alert(JSON.stringify(resp));
    //                 return;
    //             });
    //         } else {
    //             if(flg){
    //                 alert("Processing completed!");
    //                 location.reload();
    //             }
    //         }
    //     },function(resp){
    //         alert(JSON.stringify(resp));
    //         return;
    //     });
    // }

    kintone.events.on(['app.record.create.show', 'app.record.edit.show', 
        'app.record.index.edit.show'], function(event) {
        var record = event.record;
        for(var j =0; j < rowCount; j++){
            record[age[j]]['disabled'] = true;
            record[pluginDate[j]]['disabled'] = true;
        }
        return event;
    });

    kintone.events.on(['app.record.create.submit', 'app.record.edit.submit', 'app.record.index.edit.submit'], function(event) {
        var record = event.record;
        for (var j = 0; j < rowCount; j++){
            var startYear = record[year[j]]['value'];
            if (!startYear) {
                record[age[j]]['value'] = 0;
                record[pluginDate[j]]['value'] = '';
            } else {
                var a = moment();
                var b = moment(startYear);
                record[age[j]]['value'] = Number(a.diff(b, 'years')) + Number(yearBase[j]);
                record[pluginDate[j]]['value'] = moment(record[year[j]]['value']).add(Number(record[age[j]]['value']) + 1 - Number(yearBase[j]), 'years').format('YYYY-MM-DD');
            }
         }
        return event;
    });

})(kintone.$PLUGIN_ID);

